<template>
  <div class="interest-container">
    <div class="interest-header">
      <h1>同道中人筛选处</h1>
      <p class="subtitle">选择你感兴趣的内容，发现志同道合的朋友</p>
    </div>

    <div class="interest-grid">
      <div 
        v-for="interest in interests" 
        :key="interest.id"
        class="interest-item"
        :class="{ 'selected': selectedInterests.includes(interest.id) }"
        @click="toggleInterest(interest.id)"
      >
        <div class="interest-circle" :style="{ backgroundColor: interest.color + '20' }">
          <span class="interest-icon">{{ interest.icon }}</span>
        </div>
        <span class="interest-label">{{ interest.name }}</span>
      </div>
    </div>

    <div class="interest-footer">
      <button 
        class="skip-btn"
        @click="handleSkip"
      >
        跳过
      </button>
      <button 
        class="confirm-btn"
        :disabled="selectedInterests.length === 0"
        @click="handleConfirm"
      >
        我选好了（{{ selectedInterests.length }}）
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from '@/api'

const router = useRouter()
const interests = ref([])
const selectedInterests = ref([])
const loading = ref(false)

onMounted(async () => {
  await fetchInterests()
})

const fetchInterests = async () => {
  try {
    const response = await axios.get('/interests/')
    interests.value = response.data
  } catch (error) {
    console.error('获取兴趣失败:', error)
    alert('获取兴趣列表失败')
  }
}

const handleConfirm = async () => {
  if (selectedInterests.value.length === 0) {
    alert('请至少选择一个兴趣')
    return
  }

  loading.value = true

  try {
    // 获取token
    const token = localStorage.getItem('token')
        // 调试：打印token信息
    console.log('🔍 Debug - Token存在:', !!token)
    if (token) {
      console.log('🔍 Debug - Token长度:', token.length)
      console.log('🔍 Debug - Token前20字符:', token.substring(0, 20))
    }
    
    if (!token) {
      alert('请先登录')
      router.push('/login')
      return
    }

    console.log('🔍 Debug - 发送请求到: /api/interests/user/save')
    console.log('🔍 Debug - 兴趣IDs:', selectedInterests.value)

    // 直接使用fetch，确保token正确传递
    const response = await fetch('/api/interests/user/save', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ interest_ids: selectedInterests.value })
    })

    console.log('🔍 Debug - 响应状态:', response.status, response.statusText)

    if (!response.ok) {
      const errorData = await response.json()
      console.log('🔍 Debug - 错误数据:', errorData)
      throw new Error(errorData.detail || '保存失败')
    }

    const data = await response.json()
    console.log('🔍 Debug - 成功数据:', data)
    
    alert('兴趣保存成功！')
    
    // 跳转到推荐内容页
    router.push('/feed')
    
  } catch (error) {
    console.error('保存失败:', error)
    alert(error.message || '保存失败，请重试')
  } finally {
    loading.value = false
  }
}

const toggleInterest = (interestId) => {
  const index = selectedInterests.value.indexOf(interestId)
  if (index > -1) {
    selectedInterests.value.splice(index, 1)
  } else {
    selectedInterests.value.push(interestId)
  }
}

const handleSkip = async () => {
  // 确认是否跳过
  const confirmed = confirm('确定要跳过兴趣选择吗？跳过后将显示热门内容，您可以稍后在个人中心设置兴趣。')
  if (!confirmed) {
    return
  }

  loading.value = true

  try {
    // 获取token
    const token = localStorage.getItem('token')
    
    if (!token) {
      // 如果没有token，直接跳转（允许未登录用户跳过）
      router.push('/feed')
      return
    }

    // 如果有token，尝试保存空兴趣列表（清除之前的兴趣）
    // 注意：即使保存失败，也允许跳过，确保用户体验
    try {
      const response = await fetch('/api/interests/user/save', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ interest_ids: [] })
      })

      if (response.ok) {
        console.log('[跳过] 已清除用户兴趣设置')
      } else {
        console.warn('[跳过] 保存空兴趣列表失败，但继续跳过')
      }
    } catch (saveError) {
      // 保存失败不影响跳过流程
      console.warn('[跳过] 保存兴趣时出错，但继续跳过:', saveError)
    }

    // 跳转到推荐内容页
    router.push('/feed')
    
  } catch (error) {
    console.error('[跳过] 跳过过程出错:', error)
    // 即使出错，也允许跳过，确保用户不会被卡住
    router.push('/feed')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.interest-container {
  width: 100vw;
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.interest-header {
  text-align: center;
  margin-bottom: 30px;
}

.interest-header h1 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 14px;
  color: #666;
}

.interest-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  max-width: 400px;
  margin: 0 auto 80px;
}

.interest-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.interest-item:hover {
  transform: translateY(-3px);
}

.interest-item.selected .interest-circle {
  background-color: #007AFF !important;
  transform: scale(1.1);
}

.interest-item.selected .interest-label {
  color: #007AFF;
  font-weight: bold;
}

.interest-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.interest-item.selected .interest-circle {
  border-color: #007AFF;
}

.interest-icon {
  font-size: 40px;
}

.interest-label {
  font-size: 14px;
  color: #333;
  text-align: center;
}

.interest-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.skip-btn {
  width: 100%;
  padding: 12px;
  background: transparent;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.skip-btn:hover {
  background: #f5f5f5;
  border-color: #999;
  color: #333;
}

.confirm-btn {
  width: 100%;
  padding: 16px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
}

.confirm-btn:hover:not(:disabled) {
  background: #0056D6;
  transform: translateY(-2px);
}

.confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}
</style>

